<?php
namespace app\shop\controller\api;

use app\shop\library\ApiAuthController;
use app\shop\library\Member;

use app\shop\library\order\Order as OrderClass;
use app\shop\library\coupon\MemberCoupon;
use app\shop\library\pay\Pay;

class Order extends ApiAuthController
{
    public function onBefore(){
        $member_id =  Member::id();
        $re['address'] = Member::address();
        $re['memberCoupon'] = MemberCoupon::list();
        $re['payment'] = ['weixin','alipay']; 
        return $re;
    }
    
    public function onPrice(){
        $member_id =  Member::id();
        $order = new OrderClass($member_id,$this->posts);

        $status = true;
        $msg = '';
        
        if ($order->total() < 0){
            $status = false;
            $msg  = '订单总价不能小于0';
        }

        return [
            'status'=> $status,
            'msg'=> $msg,
            'goods'=> $order->list(),
            'money'=> $order->detail(),
            'pay'=> $order->total()
        ];
    }

    public function onCreate(){
        
        $member_id =  Member::id();
        $goodsList = $this->post('goods',$this->check()->type('array')->required());
        $address = $this->post('address',$this->check()->type('int')->required());
        $payment = $this->post('payment',$this->check()->type('string')->required());
        $remark = $this->post('remark',$this->check()->type('string')->maxLength(200)->default(''));

        $md5 = md5(json_encode($goodsList).$address.$member_id);
        $member_order_lock = $this->getCacheName('member_order',$md5);
        $cache = $this->app->cache();

        //防止重复提交
        if ($cache->exists($member_order_lock)){
            throw new \Exception('请勿重复提交订单');
        }
        
        //获取地址
        $addressData = $this->model('MemberAddress')->getId($address);
        if (!$addressData){
            throw new \Exception('地址不存在');
        }

        if ($addressData['member_id'] != $member_id){
            throw new \Exception('地址不存在');
        }

        $order = new OrderClass($member_id,$this->posts);
        
        if  ($order_id = $order->save(Member::$mobile,$payment,$remark,$addressData)){
            $cache->set($member_order_lock,1,60);
            return ['order_id'=>$order_id];
        }else{
            throw new \Exception('订单创建失败');
        }
        
    }
    

    public function onPay(){
        $order_id = $this->post('order_id',$this->check()->required());
        $order = $this->model('Order')->getId($order_id);
        if (!$order){
            throw new \Exception('订单不存在');
        }
        if ($order['member_id'] != Member::id()){
            throw new \Exception('订单不存在');
        }
        if ($order['status'] != 'new'){
            throw new \Exception('订单状态错误');
        }

        $pay = Pay::instance($order['payment']);

        return $pay->create($order_id,$order['money_pay'],$order['title']);
    }
}